package org.dk.poitalk.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.dk.poitalk.model.Reward;
import org.dk.poitalk.model.RewardType;
import org.dk.poitalk.service.reward.RewardService;
import org.dk.poitalk.service.user.UserService;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.LocaleResolver;

import com.google.appengine.api.datastore.KeyFactory;
import com.jappstart.model.auth.UserAccount;

@Controller
@RequestMapping("/reward")
@SessionAttributes(RewardController.REWARD)
public class RewardController {

	private static final Logger logger = Logger.getLogger(RewardController.class.getName());

	protected static final String REWARD = "reward";

	private RewardService rewardService;

	private LocaleResolver localeResolver;

	private UserService userService;

	private MessageSource messageSource;

	public RewardService getRewardService() {
		return rewardService;
	}

	@Autowired
	public void setRewardService(RewardService rewardService) {
		this.rewardService = rewardService;
	}

	public final LocaleResolver getLocaleResolver() {
		return localeResolver;
	}

	@Autowired
	public final void setLocaleResolver(final LocaleResolver localeResolver) {
		this.localeResolver = localeResolver;
	}

	public final UserService getUserService() {
		return userService;
	}

	@Autowired
	public final void setUserService(UserService userService) {
		this.userService = userService;
	}	

	public MessageSource getMessageSource() {
		return messageSource;
	}

	@Autowired
	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}

    @RequestMapping(value = "/addx", method = RequestMethod.POST)
    public final Map<String, Boolean> addx(@RequestBody final Map<String, Object> request) {
        final Map<String, Boolean> response = new HashMap<String, Boolean>();
        logger.info("add");
        Reward reward = new Reward();
        reward.setName(request.get("name").toString());
        reward.setDate(request.get("datepicker") != null ? LocalDateTime.parse(request.get("datepicker").toString()).dayOfMonth().roundCeilingCopy().toDate() : new LocalDateTime().dayOfMonth().roundCeilingCopy().toDate());
        if (request.get("type") != null) {
        	reward.setTipo(RewardType.getInstance(Integer.parseInt(request.get("type").toString())));
        }
        String username = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
        UserAccount user = this.userService.getUser(username);
        reward.setUserAccount(user);
        user.addReward(reward);
        this.userService.saveOrUpdate(user);
        return response;
    }
    
    @RequestMapping(value="/searchx", method= RequestMethod.POST)
    public @ResponseBody DataTablesResponse<Map<String, Object>> searchx(@RequestBody DataTablesRequest dataTablesRequest, HttpServletRequest request, HttpServletResponse response) {
    	DataTablesResponse<Map<String, Object>> dataTablesResponse = new DataTablesResponse<Map<String, Object>>();
    	logger.info("search");
    	Map<String, Object> mapValue = new HashMap<String, Object>();
    	String username = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
    	UserAccount user = this.userService.getUser(username);
    	List<Reward> rewardList = user.getRewards();
    	List<Map<String,Object>> listDataTable = new ArrayList<Map<String, Object>>();
    	if (rewardList != null) {
        	for (Reward reward : rewardList) {
        		
        		Map<String, Object> mapDataRows = new HashMap<String, Object>();
        		mapDataRows.put("key", reward.getKey() != null ? KeyFactory.keyToString(reward.getKey()) : StringUtils.EMPTY);
        		mapDataRows.put("name", reward.getName());
        		mapDataRows.put("datepicker", reward.getDate() != null ? reward.getDate().toString() : StringUtils.EMPTY);
        		mapDataRows.put("type", reward.getTipo() != null ? reward.getTipo().getClave() : StringUtils.EMPTY);
        		//mapDataRows.put("participantes", reward.getParticipantes() != null ? reward.getParticipantes().size() : StringUtils.EMPTY);
        		mapDataRows.put("participantes", StringUtils.EMPTY);
        		mapDataRows.put("username", reward.getUserAccount() != null ? reward.getUserAccount().getUsername() : StringUtils.EMPTY);
        		mapDataRows.put("links", StringUtils.EMPTY);
        		listDataTable.add(mapDataRows);
			}
        }
    	dataTablesResponse.echo = dataTablesRequest.echo;
    	dataTablesResponse.totalRecords = listDataTable.size();
    	dataTablesResponse.totalDisplayRecords = listDataTable.size();
    	int endSubList = ((dataTablesRequest.displayStart+dataTablesRequest.displayLength)>listDataTable.size())?listDataTable.size():(dataTablesRequest.displayStart+dataTablesRequest.displayLength);
    	dataTablesResponse.data = listDataTable.subList(dataTablesRequest.displayStart, endSubList);
    	dataTablesResponse.columns = "{key,name,datepicker,type,participantes,username,links}";
        return dataTablesResponse;
    }
    
    @RequestMapping(value="/rewardTypes", method= RequestMethod.GET)
    public @ResponseBody List<Map<String, Object>> rewardTypes(HttpServletRequest request, HttpServletResponse response) {
    	List<Map<String, Object>> typesList = new ArrayList<Map<String, Object>>();
    	logger.info("rewardTypes");
    	for (RewardType rewardType : RewardType.values()) {
    	   	Map<String, Object> mapValue = new HashMap<String, Object>();
    		mapValue.put("codigo", rewardType.getCodigo());
    		mapValue.put("descripcion", rewardType.getClave());
    		typesList.add(mapValue);
    		
		}
		return typesList;
    }
    
    @RequestMapping(value="/deletex", method= RequestMethod.POST)
    public final Map<String, Boolean> deletex(@RequestBody final Map<String, Object> request) {
    	logger.info("deletex");
    	final Map<String, Boolean> response = new HashMap<String, Boolean>();
    	String id = request.get("id").toString();
    	Reward reward = new Reward();
    	reward.setKey(KeyFactory.stringToKey(id));
    	this.rewardService.delete(reward);
    	return response;
    }
}
